<template>
	<div class="user-page table-box">
		<ProTable
			ref="proTable"
			:title="buttonsList?.length ? '' : '用户管理'"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button v-for="(item, index) in buttonsList" :key="index" :type="item.btnClass" @click="clickBtn(item.path, scope)">
					<i :class="`iconfont ${item.icon}`"></i>
					{{ item.menuName }}
				</el-button>
			</template>
			<template #status="scope">
				<el-tag v-if="scope.row.status == '0'" type="danger">停用</el-tag>
				<el-tag v-else-if="scope.row.status == '1'" type="success">启用</el-tag>
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-link
					v-if="buttonsList.find((item:any)=>item.path == 'mod')"
					type="primary"
					link
					:icon="EditPen"
					@click="openDrawer('编辑', scope.row)"
					>编辑</el-link
				>
				<el-link
					v-if="buttonsList.find((item:any)=>item.path == 'resetPwd')"
					type="primary"
					link
					:icon="EditPen"
					@click="clickBtn('resetPwd', scope.row)"
					>重置密码</el-link
				>
			</template>
		</ProTable>
		<formDialog ref="drawerRef" />
	</div>
</template>

<script setup lang="ts">
import { User } from "@/api/interface";
import { addUser, deleteUser, editUser, getUserList, resetUserPassWord } from "@/api/modules/user";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { useHandleData } from "@/hooks/useHandleData";
import { showTips } from "@/utils/util";
import { EditPen } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import formDialog from "./components/form.vue";

// const router = useRouter();

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageIndex && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		datalist: data.records,
		total: data.total,
		pageIndex: data.current,
		pageSize: data.size
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	return getUserList(params);
};
const buttonsList = ref<any>([]);
onMounted(async () => {
	// 获取页面按钮权限
	buttonsList.value = await useAuthButtons();
});
const clickBtn = (val: string, scope: any) => {
	let rows = scope.selectList ? scope.selectList : scope.id ? [scope] : scope;
	switch (val) {
		case "add":
			openDrawer("新增");
			break;
		case "del":
			if (scope.selectList.length == 0) return ElMessage.error("至少选择一条数据操作");
			batchDelete(scope.selectList.map((item: any) => item.id));
			break;
		case "mod":
			if (rows.length != 1) return ElMessage.error("请选择一条数据操作");
			openDrawer("编辑", rows[0]);
			break;
		case "resetPwd":
			console.log(rows);
			if (rows.length != 1) return ElMessage.error("请选择一条数据操作");
			useHandleData(resetUserPassWord, { username: rows[0].username }, `是否重置【${rows[0].username}】密码`).then(({ code }) => {
				showTips(code, `【${rows[0].username}】密码重置`);
			});
			break;
		case "detail":
			if (rows.length != 1) return ElMessage.error("请选择一条数据操作");
			openDrawer("查看", rows[0]);
			break;
	}
};

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "selection", fixed: "left", width: "auto" },
	{
		prop: "search",
		label: "用户名",
		search: { el: "input" },
		isShow: false
	},
	{
		prop: "username",
		label: "用户名"
	},
	{ prop: "email", label: "邮箱" },
	{
		prop: "mobile",
		label: "手机号"
	},
	{ prop: "roleName", label: "角色" },
	{ prop: "status", label: "状态" },
	{ prop: "description", label: "描述" },
	{ prop: "operation", label: "操作", fixed: "right", width: 230 }
];

// 批量删除信息
const batchDelete = async (id: string[]) => {
	let { code } = await useHandleData(deleteUser, { id: id.join(",") }, "删除所选信息");
	let ok = showTips(code, "删除用户");
	if (ok) {
		proTable.value.clearSelection();
		proTable.value.reset();
	}
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: Partial<User.ResUserList> = {}) => {
	let params = {
		title,
		rowData: { ...rowData },
		isView: title === "查看",
		api: title === "新增" ? addUser : title === "编辑" ? editUser : "",
		getTableList: proTable.value.getTableList
	};
	drawerRef.value.acceptParams(params);
};
</script>

<style lang="scss">
.user-page {
	.table-search {
		padding-bottom: 15px;
	}
}
</style>
